import numpy as np
import pandas as pd
"""
两段时间匹配，找到时间2中距离1最近的时间，并把值取出来合并到1中
"""
"""
np.random.seed(0)

base = np.array(["2013-01-01 00:00:00"], "datetime64[ns]")

a = (np.random.rand(30) * 1000000 * 1000).astype(np.int64) * 1000000
t1 = base + a
t1.sort()
print(t1)
b = (np.random.rand(10) * 1000000 * 1000).astype(np.int64) * 1000000
t2 = base + b
t2.sort()
print(t2)
idx = np.searchsorted(t1, t2) - 1
mask = idx >= 0

df = pd.DataFrame({"t1": t1[idx][mask], "t2": t2[mask]})

print(df)
"""

stock_df = pd.read_csv("E:\\MarketData\\ticks_oct_dec\stock\\20201030\\300655_20201030.csv", encoding="GBK")
bond_df = pd.read_csv("E:\\MarketData\\ticks_oct_dec\\bond\\20201030\\123031_20201030.csv", encoding="GBK")
stock_df.rename(columns={"最新":"最新股价"}, inplace=True)
t1 = np.array(stock_df["时间"])

t2 = np.array(bond_df["时间"])

idx = np.searchsorted(t1, t2, side="right") -1
mask = idx >= 0
print(mask)
t1_idx = t1[idx]
print(t1_idx)
t1_mask = t1_idx[mask]
print(t1_mask)
#df = pd.DataFrame({"t1":t1[idx][mask], "t2": t2[mask]})
#print(df)
#df.to_csv("D:\\learn_and_test_data\\pandas_time_match.csv")
bond_df.rename(columns={"时间":"转债时间"}, inplace=True)
bond_df["时间"] = t1[idx][mask]
df = pd.merge(bond_df, stock_df.loc[:,["时间","最新股价"]], how="left", on="时间")
df.to_csv("D:\\learn_and_test_data\\pandas_time_match.csv", encoding="GBK")
